const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;

const MODE_FIELDS = {
  checkIn: {
    startTime: "CheckInStartTime",
    code: "CheckInCodeOrURL",
    active: "IsCheckInActive"
  },
  checkOut: {
    startTime: "CheckOutStartTime",
    code: "CheckOutCodeOrURL",
    active: "IsCheckOutActive"
  }
};

const normalizeMode = value => {
  if (value === "checkOut" || value === "checkout") return "checkOut";
  return "checkIn";
};

const startCheckIn = async event => {
  const { groupID, mode, code } = event || {};
  const targetMode = normalizeMode(mode);
  const fields = MODE_FIELDS[targetMode];

  if (!groupID || !fields) {
    return { success: false, error: "缺少必要参数" };
  }

  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  if (!openID) {
    return { success: false, error: "未获取到用户信息" };
  }

  const trimmedCode = typeof code === "string" ? code.trim() : "";
  if (!trimmedCode) {
    return { success: false, error: "口令不能为空" };
  }

  try {
    const groupDoc = await db.collection("Activity_Group_Information").doc(groupID).get();
    const group = groupDoc.data;
    if (!group) {
      return { success: false, error: "未找到分组信息" };
    }

    const activityRes = await db
      .collection("Activity_Information")
      .doc(group.ActivityID)
      .field({ PublisherOpenID: 1 })
      .get();
    const activity = activityRes.data;

    if (!activity) {
      return { success: false, error: "未找到活动信息" };
    }

    if (activity.PublisherOpenID !== openID) {
      return { success: false, error: "仅发布者可进行签到管理" };
    }

    const updateData = {};
    updateData[fields.startTime] = db.serverDate();
    updateData[fields.code] = trimmedCode;
    updateData[fields.active] = true;

    const updateRes = await db.collection("Activity_Group_Information").doc(groupID).update({
      data: updateData
    });

    if (!updateRes.stats || updateRes.stats.updated === 0) {
      return { success: false, error: "未更新任何记录" };
    }

    return { success: true };
  } catch (error) {
    console.error("startCheckIn error", error);
    return {
      success: false,
      error: (error && error.message) || "开启签到失败"
    };
  }
};

exports.main = async (event, context) => {
  return startCheckIn(event);
};
